<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>

    <el-form
      :model="form"
      ref="form"
      size="small"
      label-width="68px"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="产品名称" prop="pdName">
        <el-input
          v-model="form.pdName"
          placeholder="请输入产品名称"
          clearable
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="pdSpecType">
        <el-input
          v-model="form.pdSpecType"
          placeholder="请输入规格型号"
          class="my-input"
        />
      </el-form-item>

      <el-form-item label="单位" prop="pdUnitType">
        <el-select v-model="form.pdUnitType" placeholder="请选择单位">
          <el-option
            v-for="u in allUnits"
            :key="u.guId"
            :label="u.guName"
            :value="u.guId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品类型" prop="pdGoodType">
        <el-select
          v-model="form.pdGoodType"
          placeholder="请选择产品类型"
        >
          <el-option
            v-for="dict in getGbsGoodType"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="产品属性" prop="pdGoodAttr">
        <el-select
          v-model="form.pdGoodAttr"
          placeholder="请选择产品属性"
        >
          <el-option
            v-for="dict in getGbsGoodAttr"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品分类" prop="pdGoodClass">
        <el-cascader
          v-model="form.pdGoodClass"
          :options="classOptions"
          :props="classProps"
          :show-all-levels="false"
          style="width: 205px"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="pdValidDate">
        <el-input-number
          v-model="getValidDatePrefix"
          :min="1"
          style="max-width: 127px"
        />
        <el-select
          v-model="getValidDateSuffix"
          placeholder="请选择有效期时间"
          style="max-width: 150px"
        >
          <el-option
            v-for="dict in getTime"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="报警天数" prop="pdAlarmDate">
        提前
        <el-input-number v-model="form.pdAlarmDate" label="请输入报警天数" :min="1" />
        天报警
      </el-form-item>
      <el-form-item label="库存上限" prop="pdMax">
        <el-input-number v-model="form.pdMax" :min="1" label="库存上限" />
      </el-form-item>

      <el-form-item label="库存下限" prop="pdMin">
        <el-input-number v-model="form.pdMin" :min="0" label="库存下限" />
      </el-form-item>
      <el-form-item label="采购价格" prop="pdOriginPrice" v-show="form.pdGoodAttr === '2'">
        <el-input-number
          v-model="form.pdOriginPrice"
          :min="0"
          label="采购价格"
          controls-position="right"
          :precision="2"
        />
      </el-form-item>

      <el-form-item label="销售价格" prop="pdSalePrice">
        <el-input-number
          v-model="form.pdSalePrice"
          :min="0"
          label="销售价格"
          controls-position="right"
          :precision="2"
        />
      </el-form-item>

      <el-form-item label="备注" prop="pdDesc" class="my-desc">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          placeholder="请输入备注"
          v-model="form.pdDesc"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">图片</div>
    </el-divider>
    <ImageUpload :limit="3" :value="getImgs" />

    <el-divider>
      <div class="my-divider">附件</div>
    </el-divider>
    <FileUpload :limit="3" :value="getFiles" />

    <!-- 上传按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />
  </div>
</template>

<script>
import { addGood, getGood, updateGood } from '@/api/yyj/gbs/good'
import { allUnit } from '@/api/yyj/gbs/unit'
import { allClass } from '@/api/yyj/gbs/class'
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'

export default {
  name: 'ChangeGood',
  components: { MyConfirmBtnGroup },
  dicts: [
    'gbs_good_type',
    'gbs_good_attr',
    'yyj_common_status',
    'yyj_common_time'
  ],
  data() {
    return {
      backPage: '/gbs/product',
      // 遮罩层
      loading: true,
      // 表单参数
      form: {
        isMaterial: '0',
        pdCode: null,
        pdProuteCode: null,
        pdName: null,
        pdStatus: '1',
        pdValidDate: '1=0',
        pdAlarmDate: 1,
        pdMax: 1,
        pdMin: 0,
        pdOriginPrice: 0,
        pdSalePrice: 0,
        pdDesc: null,
        pdSpecType: null,
        pdUnitType: null,
        pdGoodType: null,
        pdGoodAttr: null,
        pdGoodClass: null,
        gbsGoodClass: null,
        gbsGoodUnit: null,
        gbsGoodUrls: null,
        gbsGoodFiles: null
      },
      // 分类
      classOptions: [],
      classProps: {
        label: 'gcName',
        value: 'gcId',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      // 单位
      allUnits: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      // 表单校验
      rules: {
        pdName: [
          { required: true, message: '产品名称不能为空', trigger: 'blur' }
        ],
        pdSpecType: [
          { required: true, message: '规格型号不能为空', trigger: 'blur' }
        ],
        pdUnitType: [
          { required: true, message: '产品单位不能为空', trigger: 'blur' }
        ],
        pdGoodType: [
          { required: true, message: '产品类型不能为空', trigger: 'blur' }
        ],
        pdGoodAttr: [
          { required: true, message: '产品属性不能为空', trigger: 'blur' }
        ],
        pdGoodClass: [
          { required: true, message: '产品分类不能为空', trigger: 'blur' }
        ],
        pdValidDate: [
          {
            required: false,
            validator: (rule, value, callback) => {
              const v = value.substring(0, value.lastIndexOf('='))
              if (!/^\d*$/.test(v.toString())) {
                callback('请输入数字')
              }
              callback()
            }
          }
        ]
      }
    }
  },
  created() {
    const pdCode = this.$route.params && this.$route.params.pdCode
    if (!pdCode) {
      Promise.all([this.getClasses(), this.getUnits()])
    } else {
      Promise.all([
        this.getClasses(),
        this.getUnits(),
        this.getDetail(pdCode)
      ])
    }
  },
  computed: {
    getGbsGoodType() {
      return this.dict.type.gbs_good_type
    },
    getGbsGoodAttr() {
      return this.dict.type.gbs_good_attr
    },
    getStatus() {
      return this.dict.type.yyj_common_status
    },
    getTime() {
      return this.dict.type.yyj_common_time
    },
    // 有效时间
    getValidDatePrefix: {
      get() {
        if (!this.form || !this.form.pdValidDate) {
          return ''
        }
        return this.form.pdValidDate
          .toString()
          .substring(0, this.form.pdValidDate.lastIndexOf('='))
      },
      set(val) {
        this.form.pdValidDate = val + '=' + this.getValidDateSuffix
      }
    },
    getValidDateSuffix: {
      get() {
        if (!this.form || !this.form.pdValidDate) {
          return ''
        }
        return this.form.pdValidDate
          .toString()
          .substring(this.form.pdValidDate.lastIndexOf('=') + 1)
      },
      set(val) {
        this.form.pdValidDate = this.getValidDatePrefix + '=' + val
      }
    },
    getFiles() {
      if (!this.form || !this.form.gbsGoodFiles) {
        return null
      }
      return this.form.gbsGoodFiles.map((e) => e.fileName)
    },
    getImgs() {
      if (!this.form || !this.form.gbsGoodUrls) {
        return null
      }
      return this.form.gbsGoodUrls.map((e) => e.urlName)
    }
  },
  methods: {
    /** 查询详情 */
    async getDetail(pdCode) {
      const res = await getGood(pdCode)
      this.form = res.data
    },
    /** 查询分类 */
    async getClasses() {
      const res = await allClass({
        gcMaterial: '0'
      })
      this.classOptions = this.handleTree(res.data, 'gcId', 'gcFid')
    },
    /** 查询单位 */
    async getUnits() {
      const res = await allUnit()
      this.allUnits = res.data
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.$modal.loading('正在提交...')
          if (this.form.pdCode != null) {
            const res = await updateGood(this.form)
            // 添加文件
            await this.$store.dispatch('good/setGoodCode', res.data.pdCode)
            await this.$store.dispatch('good/submitData')
            this.$modal.msgSuccess('修改成功')
          } else {
            const res = await addGood(this.form)
            // 添加文件
            await this.$store.dispatch('good/setGoodCode', res.data.pdCode)
            await this.$store.dispatch('good/submitData')
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/yyj/change';

.my-img-box {
  height: 50%;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

.upload-demo .el-upload {
  width: 100%;
}
</style>
